import React, { useState, useEffect, useRef } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import i18n from 'i18n-js';
import deviceData, { pageRegExp, templatesRegExp } from '@/models/deviceData';
import deviceListModel from '@/models/deviceList';
import deviceDetail from '@/models/deviceDetail';
import { reaction, toJS, isObservable } from 'mobx';
import { observer } from 'mobx-react';
import Alert from '@/components/Alert';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import global from '@/utils/global';
import { isSameDevice, isSameAlarm } from '@/utils';
import { getProductLanguage } from '@/config/product';
import { useLanguageStore } from '@/hooks';

const alertIcon =
  'https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/495101/media/icon_warning%403x_1677493512441.png';
const faultIcon =
  'https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/495101/media/icon_fault%403x_1677493564020.png';
const warnIcon =
  'https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/495101/media/icon_abnormal%403x_1677493585122.png';

const { screenHeight } = Taro.getSystemInfoSync();

const dstyles = GStyleSheet.create({
  icon: {
    width: 82,
    height: 82,
    marginBottom: 20,
  },
  title: {
    fontSize: 20,
    fontWeight: '500',
    textAlign: 'center',
  },
  content: {
    maxHeight: screenHeight - 350,
    overflow: 'scroll',
  },
  tipText: {
    fontSize: 15,
    color: DynamicColors.subTitleTextColor,
    paddingTop: 5,
    paddingBottom: 5,
  },
  button: {
    color: DynamicColors.tintColor,
  },
});

const AlarmModalScreen: React.FC = () => {
  const [show, setShow] = useState<boolean>(false);
  const [alarmItem, setAlarmItem] = useState<any>(undefined);
  const pauseAlert = useRef<boolean>(true); // 暂时不考虑暂停弹窗的业务（设备页面再跳设备页面的嵌套）
  const deviceStack = useRef<any>([]);
  const { key: languageKey } = useLanguageStore();
  const styles = dstyles.useDynamicStyle();

  useEffect(() => {
    const queueReaction = reaction(
      () => ({ alarmQueue: deviceData.alarmQueue }),
      ({ alarmQueue }) => {
        // 如果没有登陆，不对数据变化作出反应
        if (global.token) {
          checkAlarmQueue(alarmQueue);
        }
      },
      { fireImmediately: true }
    );
    return () => {
      queueReaction();
    };
    // setTimeout(() => {
    //   console.log('alarmItem componentDidMount');
    //   setShow(true);
    //   setAlarmItem(testAlarmItem());
    // }, 3000);
  }, []);

  const checkAlarmQueue = alarmQueue => {
    const pages = Taro.getCurrentPages();
    if (alarmQueue && alarmQueue.length > 0) {
      let data: any;
      if (templatesRegExp.test(pages[pages.length - 1]?.route)) {
        // 如果当前在设备页面的话，只显示当前这个设备的告警
        data = getValidAlarmData(alarmQueue, deviceDetail.device);
      } else {
        data = getValidAlarmData(alarmQueue);
      }
      if (data) {
        // if (pauseAlert.current) {
        //   if (!isSameAlarm(data, alarmItem)) {
        //     setShow(true);
        //     setAlarmItem(data);
        //   }
        //   return;
        // }
        if (show) {
          // 已经显示了，检查当前队列最优先的是不是同一个告警，如果不是，则替换显示
          if (!isSameAlarm(data, alarmItem)) {
            setShow(true);
            setAlarmItem(data);
          }
        } else {
          setShow(true);
          setAlarmItem(data);
        }
      }
    } else {
      setShow(false);
    }
  };

  const getValidAlarmData = (alarmQueue, templateDevice?: IDevice) => {
    const invalidAlarm: any[] = [];
    const validData = alarmQueue.find(i => {
      const { device } = i;
      if (device) {
        const deviceData = deviceListModel.data.find(d => isSameDevice(d, device));
        if (deviceData) {
          if (templateDevice) {
            if (isSameDevice(templateDevice, deviceData)) {
              i.device = deviceData;
              return true;
            }
            return false;
          } else {
            i.device = deviceData;
            return true;
          }
        }
        // 告警的设备不在设备列表中，视为无效告警
        invalidAlarm.push(i);
      } else {
        invalidAlarm.push(i);
      }
      return false;
    });
    // 无效信息删除
    invalidAlarm.map(i => deviceData.delteAlarmInfo(i));
    return validData;
  };

  const onCancel = () => {
    setShow(() => {
      deviceData.delteAlarmInfo(alarmItem);
      checkAlarmQueue(deviceData.alarmQueue);
      return false;
    });
  };

  const checkClick = async () => {
    // 暂停继续弹窗的动作，除非有更高级别的弹窗
    const { device } = alarmItem;
    // pauseAlert.current = true;
    // 路由参数暂时不传
    const pages = Taro.getCurrentPages();
    const currentRoute = pages[pages.length - 1]?.route;
    if (pageRegExp.test(currentRoute)) {
      /**
       * 在外层点击故障查看，正常跳转
       * 安卓手机跳转控制页后关闭所有故障，返回主体App时会有故障弹窗闪烁现象
       * 这里的处理是调tempChangeAlarmQueue，在跳转前手动清空故障队列，之后再恢复
       */
      deviceData.delteAlarmInfo(alarmItem);
      deviceStack.current.push(alarmItem);
      await deviceData.tempChangeAlarmQueue();
      checkAlarmQueue(deviceData.alarmQueue);
      setShow(false);
      deviceData.goToDetailPage(device);
      return;
    }
    setShow(() => {
      deviceData.delteAlarmInfo(alarmItem);
      deviceStack.current.push(alarmItem);
      checkAlarmQueue(deviceData.alarmQueue);
      return false;
    });
    if (templatesRegExp.test(currentRoute)) {
      console.log('已经在控制页了，不跳转');
      return;
    }
    deviceData.goToDetailPage(device);
  };

  // const checkDeviceStack = () => {
  //   const alarmArr = deviceStack.current.splice(deviceStack.current.length - 1, 1);
  //   alarmArr.map(i => deviceData.delteAlarmInfo(i));
  //   if (deviceStack.current.length < 1) {
  //     pauseAlert.current = false;
  //     setTimeout(() => {
  //       checkAlarmQueue(deviceData.alarmQueue);
  //     }, 300);
  //   }
  // };

  // const testAlarmItem = () => {
  //   const device = deviceListModel.data[0];
  //   return {
  //     type: 'fault',
  //     action: {
  //       content: [
  //         {
  //           title: 'test_1',
  //         },
  //         {
  //           rowText: 'test_2',
  //         },
  //         {
  //           rowText: 'test_3',
  //         },
  //         {
  //           rowText: 'test_4',
  //         },
  //       ],
  //     },
  //     name: 'ALARM_1',
  //     device: {
  //       name: '气体报警器',
  //       productKey: '094b51a1227147939823050defa1ccab',
  //     },
  //     device,
  //   };
  // };

  const getComponent = alarmItem => {
    let icon = faultIcon;
    let titleColor = DynamicColors.normalTextColor;
    const {
      type,
      action: { content },
      name,
      device: { name: deviceName, productKey },
    } = alarmItem;
    if (type === 'alerts') {
      icon = alertIcon;
    } else if (type === 'warn') {
      icon = warnIcon;
    } else {
      icon = faultIcon;
    }
    const titleText = `${(deviceName || '') + getProductLanguage(productKey, languageKey, name)}!`;
    const title = (
      <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: 20 }}>
        <Image src={icon} style={styles.icon} />
        <Text style={{ ...styles.title, color: titleColor }}>{titleText}</Text>
      </View>
    );
    const contentView = (
      <ScrollView enhanced showScrollbar={false} bounces={false} style={styles.content}>
        {content.map((i, index) => {
          const { title, rowText } = isObservable(i) ? toJS(i) : i;
          let text = '';
          if (title) {
            text = getProductLanguage(productKey, languageKey, title);
            return (
              <Text
                key={index}
                style={{ ...styles.tipText, textAlign: 'center', paddingTop: 0, paddingBottom: 20, marginTop: 0 }}>
                {text}
              </Text>
            );
          } else if (rowText) {
            text = getProductLanguage(productKey, languageKey, rowText);
            return (
              <View key={index} style={{ display: 'flex', textAlign: 'center' }}>
                <Text style={{ ...styles.tipText, fontSize: 7, top: 3 }}>●</Text>
                <Text style={{ ...styles.tipText, paddingTop: 0, paddingLeft: 6, paddingRight: 6, textAlign: 'left' }}>
                  {text}
                </Text>
              </View>
            );
          }
        })}
      </ScrollView>
    );
    return { title, content: contentView };
  };
  return (
    <>
      {!!alarmItem ? (
        <Alert
          title={getComponent(alarmItem).title}
          titleStyle={{ paddingBottom: 8 }}
          content={getComponent(alarmItem).content}
          visible={show}
          cancelText={<Text style={styles.button}>{i18n.t('CLOSE')}</Text>}
          okText={<Text style={styles.button}>{i18n.t('CHECK')}</Text>}
          onCancel={onCancel}
          onConfirm={checkClick}
          zIndex={9999}
        />
      ) : null}
    </>
  );
};

export default observer(AlarmModalScreen);
